import React, { useEffect, useState } from 'react';
import { Upload, Button, Table, Image, Space, message as antdMessage, } from 'antd'
import axios from 'axios'
import { RcFile, UploadChangeParam, UploadFile, } from 'antd/es/upload';

interface ListRawState {
  name: string
  url: string
}

const App = () => {
  const [list, setList] = useState<ListRawState[]>([]);

  const getList = () => {
    axios.get('/api/upload/images/list').then(resp => {
      setList(resp.data.data.objects.map((v: any, i: number) => {
        return {
          name: v.name,
          url: v.url,
          key: i
        }
      }))
    })
  }
  const handleDelete = async (name: string) => {
    await axios.delete('/api/upload/images/list', { params: { name } })
    await getList()
    antdMessage.success('删除成功')
  }

  const columns = [{
    key: 'name',
    dataIndex: 'name',
    title: "文件名称"
  }, {
    key: 'url',
    dataIndex: 'url',
    title: "图片",
    render(url: string) {
      const index = url.lastIndexOf('.')
      if(url.slice(index) === '.mp4') {
        return  <video src={url} controls height={200} width={300}></video>
      } else {
        return <Image height={50} src={url}></Image>
      }
    }
  }, {
    key: 'down',
    dataIndex: 'url',
    title: '操作',
    render(url: string, row: ListRawState) {
      return <Space>
        <Button type="primary" onClick={() => window.open(url)}>下载</Button>
        <Button type="primary" danger onClick={() => handleDelete(row.name)}>删除</Button>
      </Space>
    }
  }]

  const onChange = async (e: UploadChangeParam<UploadFile<any>>) => {
    if (e.fileList.every(v => v.response)) {
      await getList();
      antdMessage.success('上传成功')
    }
  }

  const beforeUpload = (file: RcFile) => {
    console.log(file.type)
    if (file.type.includes('image') || file.type.includes('video')) {
      return true
    }

    return Upload.LIST_IGNORE

  }

  useEffect(() => {
    getList()
  }, [])

  return (
    <div>
      <div style={{ display: 'flex' }}>
        <div>
          <div style={{ height: 300, width: '30vw' }}>
            <Upload.Dragger beforeUpload={e => beforeUpload(e)} multiple action="/api/upload/images" onChange={e => onChange(e)} directory>
              <Button type="primary">上传文件夹</Button>
            </Upload.Dragger>
          </div>

          <div style={{ height: 300, width: '30vw' }}>
            <Upload.Dragger beforeUpload={e => beforeUpload(e)} multiple action="/api/upload/images" onChange={e => onChange(e)} maxCount={6}>
              <Button type="primary" >上传文件</Button>
            </Upload.Dragger>
          </div>

        </div>

        <div style={{ flex: 1, marginLeft: 20 }}>
          <Table dataSource={list} columns={columns}></Table>
        </div>
      </div>

    </div>
  )
}


export default App